<template>
  <div class="department-container">
    <div class="app-container">
      <el-card>
        <el-row type="flex" justify="end">
          <el-button type="success" size="small">
            <router-link to="/import">
              导 入 excel
            </router-link>
          </el-button>

          <el-button type="warning" size="small" @click="excelBack">导 出 excel</el-button>
          <el-button type="primary" size="small" @click="addVisible=true">+ 新增员工</el-button>
        </el-row>
      </el-card>
      <el-card>
        <el-table
          :data="roleList"
          border
          style="width: 100%"
        >
          <el-table-column
            label="序号"
            width="150"
          >
            <template slot-scope="{$index}">
              {{ ($index +1 )+ (q.page-1)*q.size }}
            </template>
          </el-table-column>
          <el-table-column
            prop="username"
            label="姓名"
            width="150"
            sortable
          />
          <el-table-column
            prop="mobile"
            label="手机号"
            width="150"
            sortable
          />
          <el-table-column
            prop="workNumber"
            label="工号"
            width="150"
            sortable
          />
          <el-table-column
            label="聘用形势"
            width="200"
            sortable
          >
            <template slot-scope="scope">
              {{ scope.row.formOfEmployment==1 ?'正式' : '试用' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="departmentName"
            label="部门"
            width="150"
            sortable
          />
          <el-table-column
            prop="timeOfEntry"
            label="入职时间"
            width="150"
            sortable
          >
            <template slot-scope="{row}">
              {{ formatDate(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column
            label="是否在职"
            width="150"
            sortable
          >
            <template slot-scope="scope">
              {{ scope.row.inServiceStatus==1 ? '在职' : '离职' }}
            </template>
          </el-table-column>
          <el-table-column
            label="状态"
            width="120"
            sortable
          >
            <template slot-scope="{row}">
              {{ row.enableState==1 ? '可用' : '不可用' }}
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="280"
            align="center"
          >
            <template slot-scope="scope">
              <el-row type="flex" justify="space-between">
                <el-button
                  type="text"
                  @click="$router.push({
                    name:'detail',
                    params:{
                      id:scope.row.id
                    }
                  })"
                >查看</el-button>
                <el-button type="text">转正</el-button>
                <el-button type="text">调岗</el-button>
                <el-button type="text">离职</el-button>
                <el-button type="text" @click="showAllotDialog(scope.row)">角色</el-button>
                <el-button type="text" @click="delemp(scope.row.id)">删除</el-button>
              </el-row>

            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="end" style="padding:15px 0 5px">
          <el-pagination
            :page-size="q.size"
            layout="total, prev, pager, next"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <el-dialog
          title="编辑员工"
          :visible.sync="addVisible"
          width="50%"
          :before-close="handleClose"
        >
          <emp-dialog :departall="departall" @success="success" />
        </el-dialog>
        <el-dialog
          title="分配角色"
          :visible.sync="allotVisible"
          width="50%"
          :before-close="allotclose"
        >
          <allot-dialog v-if="allotVisible" :role-ids="roleIds" :roleid="roleid" @allotclose="allotclose" />

        </el-dialog>
      </el-card>
    </div>
  </div>
</template>
<script>
import { getUsers, delEmployee } from '@/api/employees'
import dayjs from 'dayjs'
import { getDepartments } from '@/api/departments.js'
// import { getUserDetailById } from '@/api/user'
// 转树形结构
import { tranListToTreeData } from '@/utils/tree.js'
import empDialog from './empDialog.vue'
import allotDialog from './allotDialog.vue'
export default {
  components: {
    empDialog,
    allotDialog
  },
  data() {
    return {
      roleList: [],
      q: {
        page: 1,
        size: 10
      },
      total: 0,
      addVisible: false,
      allotVisible: false,
      //   部门
      departall: {},
      //   当前所点击的角色id
      roleid: '',
      //   权限id组
      roleIds: []
    }
  },
  created() {
    //   初始化所有角色列表
    this.initRole()
    // 查询所有部门
    this.initdepartall()
  },
  methods: {
    async initRole() {
      const res = await getUsers(this.q)
      if (res.code === 10000) {
        this.roleList = res.data.rows
        this.total = res.data.total
      } else {
        console.log('获取列表失败，请联系管理员')
      }
    },
    formatDate(date) {
      return dayjs(date).format('YYYY-MM-DD')
    },
    handleSizeChange(change) {
      console.log(change, 1)
    },
    handleCurrentChange(page) {
      this.q.page = page
      this.initRole()
    },
    // 添加角色框关闭
    handleClose() {
      this.addVisible = false
    },
    delemp(id) {
      this.$confirm('该操作将永久删除该员工信息是否继续?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          await delEmployee(id)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          //   初始化所有角色列表
          this.initRole()
        } catch (err) {
          console.log(err)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 查询所有部门
    async  initdepartall() {
      const res = await getDepartments()
      if (res.code === 10000) {
        this.departall = tranListToTreeData(res.data.depts)
      }
    },
    success() {
      // 关闭弹框
      this.addVisible = false
      //   刷新页面
      this.initRole()
    },
    // 导出excel表
    excelBack() {
      import ('@/vendor/Export2Excel').then(async excel => {
        const res = await getUsers(this.q.page, this.total)
        const list = res.data.rows
        const { header, data } = this.formatData(list)
        excel.export_json_to_excel({
          multiHeader: [['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b']],
          merges: ['A1:B1'],
          header: header,
          data: data, // 具体数据 必填
          filename: '传智-员工信息表', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    formatData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      let header = []
      let data = []
      const one = list[0]
      if (!one) {
        return { header, data }
      }
      header = Object.keys(one).map(key => {
        return map[key]
      })
      //   data把 list中每一个对象转成 对应的 value数组
      data = list.map(obj => {
        return Object.values(obj)
      })
      return { header, data }
    },
    // 展示分配角色对话框
    async showAllotDialog(row) {
      this.allotVisible = true
      //  根据角色id拿到权限id数组
      this.roleid = row.id
      this.getInfo(row.id)
    //   const res = await getUserDetailById(row.id)
    //   this.roleIds = res.data.roleIds
    },
    // 角色关闭事件
    allotclose() {
      this.allotVisible = false
    }
  }
}
</script>
<style lang="scss" scoped>
.el-card{
    margin-bottom: 10px;
    ::v-deep.el-card__body{
        padding: 20px 20px 10px;
    }
}
</style>
